//
//  VideoBrowserCell.swift
//  MyVideo
//
//  Created by han on 2021/4/20.
//

import UIKit
import AVKit

protocol VideoBrowserCellDelegate: AnyObject {
    func videoBrowserCellTapped(_ cell: VideoBrowserCell)
}

class VideoBrowserCell: UICollectionViewCell {
    var playerViewControllerCoordinator: VideoPlayerViewControllerCoordinator? {
        didSet {
            guard playerViewControllerCoordinator != oldValue else { return }
            if oldValue?.playerViewControllerIfLoaded?.viewIfLoaded?.isDescendant(of: videoContainerView) == true {
                oldValue?.removeFromParentIfNeeded()
            }
        }
    }
    
    weak var delegate: VideoBrowserCellDelegate?
    
    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var thumbnailImageView: UIImageView!
    @IBOutlet weak var videoContainerView: UIView!
    @IBOutlet weak var titleLabel: UILabel!
    
    @IBOutlet weak var showVideoButton: UIButton!
   
    
    @IBAction func showVideoAction(_ sender: UIButton) {
        delegate?.videoBrowserCellTapped(self)
    }
    
    var debugHud: DebugHUD? {
        didSet {
            guard oldValue != debugHud else { return }
            oldValue?.removeFromSuperview()
            if let debugHud = debugHud {
                videoContainerView.insertSubview(debugHud, at: 0)
                debugHud.translatesAutoresizingMaskIntoConstraints = false
                NSLayoutConstraint.activate([
                    debugHud.centerXAnchor.constraint(equalTo: videoContainerView.centerXAnchor),
                    debugHud.topAnchor.constraint(equalTo: videoContainerView.topAnchor),
                    debugHud.widthAnchor.constraint(equalTo: videoContainerView.widthAnchor),
                    debugHud.heightAnchor.constraint(equalTo: videoContainerView.heightAnchor)
                ])
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        contentView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        contentView.layer.cornerCurve = .continuous
        contentView.layer.cornerRadius = 12.0
        containerView.clipsToBounds = true
        containerView.layer.cornerCurve = .continuous
        containerView.layer.cornerRadius = 8.0
    }
    
    deinit {
        playerViewControllerCoordinator = nil
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        playerViewControllerCoordinator = nil
        debugHud = nil
    }
}
